<template>
	<div class="zs-table-page-container">
		<div class="zs-card-sm zs-space-bottom zs-layout-flex-row zs-layout-justify-between">
			<div>
				<el-select v-model="queryParams.projectCode" class="zs-select-md zs-space-right-sm" placeholder="项目" @change="changeProject" clearable filterable>
					<el-option v-for="item in projectList" :key="item.projectCode" :label="item.projectName" :value="item.projectCode" />
				</el-select>
				<el-select v-model="queryParams.communityId" collapse-tags collapse-tags-tooltip class="zs-select-md zs-space-right-sm" placeholder="区域" clearable filterable @change="changeArea">
					<el-option v-for="item in areaList" :key="item.communityId" :label="item.communityName" :value="item.communityId" />
				</el-select>
				<el-select v-model="queryParams.buildId" class="zs-select-md zs-space-right-sm" placeholder="楼宇" @change="changeBuild" clearable filterable>
					<el-option v-for="item in buildList" :key="item.buildId" :label="item.buildName" :value="item.buildId" />
				</el-select>
				<el-popover popper-class="zs-popper" placement="bottom-end" trigger="click">
					<template #reference>
						<el-button class="zs-btn-square-solid" :class="{ 'zs-btn-square-solid-active': queryParams.houseId }">
							<el-icon>
								<MoreFilled />
							</el-icon>
						</el-button>
					</template>
					<template #default>
						<el-select v-model="queryParams.houseId" class="zs-select-md zs-space-right-sm" placeholder="房间" @change="queryList" clearable filterable :teleported="false">
							<el-option v-for="item in roomList" :key="item.houseId" :label="item.simpleHouseNumber" :value="item.houseId" />
						</el-select>
					</template>
				</el-popover>
				<el-button class="zs-btn-plain" @click="queryList"> 查询 </el-button>
			</div>
			<div>
				<el-button class="zs-btn-plain zs-btn-md" @click="handleDownload">
					<el-icon class="el-icon--left"> <Upload /> </el-icon>导出
				</el-button>
			</div>
		</div>

		<!-- teble -->
		<div class="zs-card zs-table-page-content">
			<el-table class="zs-table-page-main zs-table-first-row-special" :data="tableData.data" v-loading="tableData.loading" stripe>
				<el-table-column label="序号" width="60" align="center">
					<template #default="scope">
						<span v-if="scope.$index == 0">合计</span>
						<span v-else>{{ scope.$index + (tableData.currentPage - 1) * curPageSize }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="communityName" label="区域" show-overflow-tooltip align="left" :formatter="defaultTableData" />
				<el-table-column prop="buildName" label="楼宇" width="80" show-overflow-tooltip align="left" :formatter="defaultTableData" />
				<el-table-column label="房间号" show-overflow-tooltip align="left">
					<template #default="{ row }">
						<span class="zs-link cursor-pointer" @click="goRoomPage(row)">{{ row.simpleHouseNumber }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="cuName" label="客户" align="left" :formatter="defaultTableData" show-overflow-tooltip />
				<el-table-column prop="totarrears" label="全部欠款" align="right" :formatter="defaultTableData" show-overflow-tooltip />
				<el-table-column prop="curarrears" label="当期欠款" align="right" :formatter="defaultTableData" show-overflow-tooltip />
				<el-table-column prop="hisarrears" label="历史欠款" align="right" :formatter="defaultTableData" show-overflow-tooltip />
				<el-table-column prop="thyarrears" :label="`${currentYear}欠款`" align="right" :formatter="defaultTableData" show-overflow-tooltip />
				<el-table-column prop="layarrears" :label="`${currentYear - 1}欠款`" align="right" :formatter="defaultTableData" show-overflow-tooltip />
				<el-table-column prop="pryarrears" :label="`${currentYear - 2}欠款`" align="right" :formatter="defaultTableData" show-overflow-tooltip />
				<el-table-column prop="befyarrears" :label="`${currentYear - 3}年及以上欠款`" align="right" :formatter="defaultTableData" width="135" show-overflow-tooltip />
				<el-table-column prop="isRelPar" label="是否关联方" align="center" :formatter="defaultTableData" show-overflow-tooltip />
				<el-table-column prop="resePerson" label="责任人" align="left" :formatter="defaultTableData" show-overflow-tooltip />
			</el-table>
			<div class="zs-space-top-sm zs-table-page-pagination">
				<el-pagination v-model:currentPage="tableData.currentPage" v-model:page-size="curPageSize" :page-sizes="curPageSizes" :small="true" :background="true" layout="total, sizes, prev, pager, next, jumper" :total="tableData.total" @size-change="pageChange('size', $event)" @current-change="pageChange('page', $event)" />
			</div>
		</div>
	</div>
</template>

<script setup>
	import { ref, reactive } from 'vue';
	import { useStore } from 'vuex';
	import { useRoute, useRouter } from 'vue-router';
	import { toThousands } from '@/utils/number-util';
	import { getProjectDropdownApi } from '@/api/SpecialReport/propertyReceivable';
	import { downloadNewFile } from '@/utils/publicUtils';
	import detailApi from '@/api/Property/detailPages';

	const route = useRoute();
	const router = useRouter();
	const store = useStore();
	const curPageSizes = ref(store.state.uiPageSizes);
	const curPageSize = ref(store.state.uiPageSizeDefault);

	const currentYear = new Date().getFullYear();
	// 列表 filed
	let tableData = reactive({
		currentPage: 1,
		total: 0,
		loading: false,
		data: [],
	});

	//查询条件
	let queryParams = reactive({ projectCode: route.query.projectCode, pageNum: 1, pageSize: curPageSize.value });

	// 列表数据源
	const queryList = async () => {
		tableData.loading = true;
		let res = await detailApi.debtAnalyseInfoListApi(queryParams);
		if (res.data.errorCode !== 200) return;
		tableData.data = res.data.data.list || [];
		if (res.data.data.list && res.data.data.list.length > 0) {
			tableData.data.unshift(res.data.data);
		}
		initData(tableData.data);
		tableData.total = res.data.totalCount || 0;
		tableData.loading = false;
	};

	const initData = list => {
		list.forEach(item => {
			let moneyFiledList = ['totarrears', 'curarrears', 'hisarrears', 'thyarrears', 'layarrears', 'pryarrears', ' befyarrears'];
            moneyFiledList.forEach(filed => {
                item[filed] = toThousands(item[filed]);
            })
		});
	};

	//选择项目联动
	const changeProject = () => {
		queryParams.communityId = '';
		queryParams.buildId = '';
		queryParams.houseId = '';
		areaList.value = [];
		buildList.value = [];
		roomList.value = [];
		getAeraList();
	};

	//切换区域
	const changeArea = () => {
		queryParams.buildId = '';
		queryParams.houseId = '';
		buildList.value = [];
		roomList.value = [];
		getBuildList();
	};

	//切换楼宇重置房间列表 重新查询数据
	const changeBuild = () => {
		queryParams.houseId = '';
		roomList.value = [];
		getRoomList();
	};

	//获取区域下拉列表
	const areaList = ref([]);
	const getAeraList = async () => {
		let res = await detailApi.getRegionDropdownDropdownApi({ projectCode: queryParams.projectCode });
		if (res.data.errorCode != 200) return;
		areaList.value = res.data.data;
	};

	//获取楼栋下拉列表
	const buildList = ref([]);
	const getBuildList = async () => {
		if (!queryParams.communityId) return
		let res = await detailApi.getBuildDropdownApi({ projectCode: queryParams.projectCode, communityid: queryParams.communityId });
		if (res.data.errorCode != 200) return;
		buildList.value = res.data.data;
	};

	//获取房间下拉列表
	const roomList = ref([]);
	const getRoomList = async () => {
		if (!queryParams.buildId) return
		let res = await detailApi.getRoomDropdownApi({ projectCode: queryParams.projectCode, buildId: queryParams.buildId });
		if (res.data.errorCode != 200) return;
		roomList.value = res.data.data;
	};

	//项目列表
	let projectList = ref([]);
	const getProjectList = async () => {
		let res = await getProjectDropdownApi({ projectCode: queryParams.projectCode });
		if (res.data.errorCode != 200) return;
		projectList.value = res.data.data;
	};

	// 分页
	const pageChange = (type, size) => {
		if (type == 'size') {
			queryParams.pageSize = size;
		} else {
			queryParams.pageNum = size;
		}
		queryList();
	};

	// 导出
	const handleDownload = async () => {
		const fileName = `欠款分析报表.xls`;
		let fileData = await detailApi.debtAnalyseInfoExportApi(queryParams);
		downloadNewFile(fileData.data, fileName);
	};

	//房间详情
	const goRoomPage = (row) => {
		router.push({
			path: '/page/routeController/index',
			query: {
				rid: 'Property_DashBoard_DebtAnalyse_Roominfo',
				rTitle: '欠款房间明细',
				menuKey: route.query.menuKey,
				pageKey: route.query.pageKey,
				projectCode: queryParams.projectCode,
                communityId: row.communityid,
                buildId: row.buildid,
                houseId: row.houseid,
			},
		});
	};

	const defaultTableData = (row, column, cellValue, index) => {
		let emptyVal = index == 0 ? '' : '-';
		return cellValue || cellValue === 0 ? cellValue : emptyVal;
	};

	getProjectList();
	getAeraList();
	queryList();
</script>